﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Meraz.Core.Model;
using Meraz.Core.Repositories;
using Ninject;

namespace Meraz.Core.Commands
{
    public interface ISaveTwitterUserCommand : ICommand<TwitterUser> {
        ITwitterUserRepository Repository { get; set; }
    }
    public class SaveTwitterUserCommand : BaseCommand, ISaveTwitterUserCommand
    {
        public SaveTwitterUserCommand()
        {
            Repository = new TwitterUserRepository();
        }
        public SaveTwitterUserCommand(ITwitterUserRepository repository) {
            Repository = repository ?? new TwitterUserRepository();
        }
        public ITwitterUserRepository Repository { get; set; }
        public TwitterUser Result { get; set; }
        public virtual void Execute()
        {
            if (Result == null)
                throw new ApplicationException("Illegal state: User must be set.");

            TwitterUser existing = null;
            if (Result.ID > 0)
            {
                existing = Repository.GetById(Result.ID);
                if (existing == null)
                    throw new ApplicationException("Invalid User ID");
                existing.IsBlog = Result.IsBlog;
                existing.IsNewspaper = Result.IsNewspaper;
                existing.IsTopJournalist = Result.IsTopJournalist;
                existing.IsTopPolitical = Result.IsTopPolitical;
            }
            else
            {
                if (string.IsNullOrWhiteSpace(Result.Name))
                    throw new ApplicationException("User must have a Name or ID.");
                existing = Repository.GetByUsername(Result.Name);
                if (existing == null)
                {
                    Result.ID = 0;//eliminate negative ID?
                    Repository.Add(Result);
                }else{
                    existing.IsBlog = Result.IsBlog;
                    existing.IsNewspaper = Result.IsNewspaper;
                    existing.IsTopJournalist = Result.IsTopJournalist;
                    existing.IsTopPolitical = Result.IsTopPolitical;
                }
            }
            Commit();
        }
    }
}
